﻿namespace DepartmentSpecificStoreView
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Text.RegularExpressions;

    using Microsoft.SharePoint;

    public class DepartmentInformationBL
    {
        #region Fields

        List<DepartmentFields> _AvailableFields;
        List<DepartmentInformation> _DepartmentList;
        List<UIGridInfo> _UiGridWidth;

        #endregion Fields

        #region Properties

        public List<DepartmentFields> AvailableFields
        {
            get
            {
                if ( _AvailableFields == null )
                    _AvailableFields = new List<DepartmentFields>( );
                return _AvailableFields;
            }
        }

        public List<DepartmentInformation> DepartmentList
        {
            get
            {
                if ( _DepartmentList == null )
                    _DepartmentList = new List<DepartmentInformation>( );
                return _DepartmentList;
            }
        }

        public List<UIGridInfo> UiGridWidth
        {
            get
            {
                if ( _UiGridWidth == null )
                    _UiGridWidth = new List<UIGridInfo>( );
                return _UiGridWidth;
            }
            set
            {
                _UiGridWidth = value;
            }
        }

        #endregion Properties

        #region Methods

        public static string Strip( string text )
        {
            return Regex.Replace( text, @"<(.|\n)*?>", string.Empty );
        }

        public void GetAllListRowData( ref DataRow dataRow, SPWeb storeWeb, string projectID, string listName )
        {
            TargetFieldsDataCollectionBL target = new TargetFieldsDataCollectionBL( );

            string currentCode = "";

            SPList departmentFieldsView;
            SPList allOrderingFields = storeWeb.Lists[ "Department Ordering Lookup" ];
            SPListItemCollection singleDeptFieldsView;
            string currentFieldName = "";
            string currentInternalFieldName = "";
            string currentFieldType = "";

            string currentValue = "";

            SPQuery sourceUserDepartments = new SPQuery( );
            SPQuery singleDepartments = new SPQuery( );
            sourceUserDepartments.Query = "<Where><Eq><FieldRef Name='Department_x0020_Owner' /><Value Type='Text'>" + listName + "</Value></Eq></Where>";

            SPListItemCollection allFieldViews = allOrderingFields.GetItems( sourceUserDepartments );
            if ( allFieldViews.Count == 0 )
                return;

            int i = 0;
            for ( int j = 0; j < allFieldViews.Count; j++ )
            {
                currentFieldName = allFieldViews[ j ][ "Field Name" ].ToString( );
                currentInternalFieldName = allFieldViews[ j ][ "Internal Field Name" ].ToString( );
                currentFieldType = allFieldViews[ j ][ "FieldType" ].ToString( );
                departmentFieldsView = storeWeb.Lists[ allFieldViews[ j ][ "Source Department" ].ToString( ) ];
                singleDepartments = new SPQuery( );

                if ( allFieldViews[ j ][ "Source Department" ].ToString( ).Trim( ).Equals( "Stores Detail" ) )
                {
                    singleDepartments.Query = "<Where><Eq><FieldRef Name='Reference_x0020__x0023_' /><Value Type='Number'>" + projectID + "</Value></Eq></Where>";
                    singleDepartments.ViewFields = "<FieldRef Name='" + currentInternalFieldName + "'/>";
                }
                else
                {
                    singleDepartments.Query = "<Where><Eq><FieldRef Name='Store_x0020_Reference_x0020_ID' /><Value Type='Number'>" + projectID + "</Value></Eq></Where>";
                    singleDepartments.ViewFields = "<FieldRef Name='" + currentInternalFieldName + "'/>";
                }

                singleDeptFieldsView = departmentFieldsView.GetItems( singleDepartments );

                if ( allFieldViews[ j ][ "Source Department" ].ToString( ).Trim( ).Equals( "Stores Detail" ) )
                {
                    currentCode = allFieldViews[ j ][ "Source Department" ].ToString( ).Trim( );
                    if ( singleDeptFieldsView[ 0 ][ currentFieldName ] == null )
                        currentValue = "";
                    else
                        currentValue = singleDeptFieldsView[ 0 ][ currentFieldName ].ToString( );
                }
                else
                {
                    currentCode = target.GetDepartmentAbbriviations( storeWeb, allFieldViews[ j ][ "Source Department" ].ToString( ) );

                    if ( !dataRow.Table.Columns.Contains( currentFieldName.Trim( ) + " - " + currentCode ) )
                    {
                        if ( singleDeptFieldsView[ 0 ][ currentFieldName ] == null )
                            currentValue = "";
                        else
                            currentValue = singleDeptFieldsView[ 0 ][ currentFieldName ].ToString( );
                    }
                    else
                    {
                        if ( singleDeptFieldsView[ 0 ][ currentFieldName ] == null )
                            currentValue = "";
                        else
                            currentValue = singleDeptFieldsView[ 0 ][ currentFieldName ].ToString( );
                        currentFieldName = currentFieldName + " - " + currentCode;
                    }
                }

                if ( currentFieldType.Equals( "DateTime" ) )
                    dataRow[ currentFieldName ] = Strip( DateStringCleanup( currentValue ) );
                else
                    dataRow[ currentFieldName ] = Strip( currentValue );
                i++;
            }
        }

        public void GetAllListRowDataFromCollection( ref DataRow dataRow, SPWeb storeWeb, string projectID, string listName, List<DepartmentViewReferences> uniqueDataAccess, bool currentWidthInfo )
        {
            string currentCode = "";

            SPList allOrderingFields = storeWeb.Lists.TryGetList( "Department Ordering Lookup" ); // storeWeb.Lists[ "Department Ordering Lookup" ];
            if ( allOrderingFields == null )
                return;

            string currentFieldName = "";
            string currentFieldType = "";
            string currentInternalFieldName = "";
            string currentValue = "";

            SPQuery sourceUserDepartments = new SPQuery( );
            sourceUserDepartments.Query = "<Where><Eq><FieldRef Name='Department_x0020_Owner' /><Value Type='Text'>" + listName + "</Value></Eq></Where>";

            SPListItemCollection allFieldViews = allOrderingFields.GetItems( sourceUserDepartments );
            if ( allFieldViews.Count == 0 )
                return;

            DataRow[ ] dr;
            string originalCommentsValue = "";
            bool commentsField = false;

            string currentOrder = "";
            string currentWidth = "";

            DataRow drFixed = null;

            for ( int j = 0; j < allFieldViews.Count; j++ )
            {
                commentsField = false;
                try
                {
                    currentOrder = allFieldViews[ j ][ "Order Number" ].ToString( );
                    currentWidth = allFieldViews[ j ][ "Column Width" ].ToString( );
                    if ( currentWidthInfo )
                        UiGridWidth.Add( new UIGridInfo( int.Parse( currentWidth ), int.Parse( currentOrder ) ) );
                    currentFieldName = allFieldViews[ j ][ "Field Name" ].ToString( );
                    currentInternalFieldName = allFieldViews[ j ][ "Internal Field Name" ].ToString( );

                    currentFieldType = allFieldViews[ j ][ "FieldType" ].ToString( );

                    if ( currentFieldName.Trim( ).StartsWith( "Comments" ) )
                        commentsField = true;

                    foreach ( DepartmentViewReferences deptCollections in uniqueDataAccess )
                    {
                        if ( deptCollections.DepartmentName.Trim( ).Equals( allFieldViews[ j ][ "Source Department" ].ToString( ).Trim( ) ) )
                        {
                            currentCode = deptCollections.DepartmentCode;
                            if ( deptCollections.DepartmentName.Equals( "Stores Detail" ) )
                            {
                                dr = deptCollections.DepartmentDataTable.Select( "Reference_x0020__x0023_='" + projectID + "'" );
                                drFixed = dr[ 0 ];
                                break;
                            }
                            else
                            {
                                dr = deptCollections.DepartmentDataTable.Select( "Store_x0020_Reference_x0020_ID='" + projectID + "'" );
                                drFixed = dr[ 0 ];
                                break;
                            }
                        }
                    }
                    //we have the data now....lets map a field

                    //get the code
                    if ( !currentFieldName.Trim( ).Equals( "Modified By" ) )
                        currentValue = drFixed[ currentInternalFieldName ].ToString( );
                    else
                        currentValue = drFixed[ "Editor" ].ToString( );
                    try
                    {
                        if ( dataRow.Table.Columns.Contains( currentFieldName.Trim( ) + " - " + currentCode ) )
                        {
                            currentFieldName = currentFieldName + " - " + currentCode;
                        }
                    }
                    catch
                    {
                        ConsumeError( );
                    }
                    try
                    {
                        if ( !commentsField )
                        {
                            if ( currentFieldType.Equals( "DateTime" ) )
                                dataRow[ currentFieldName ] = Strip( DateStringCleanup( currentValue ) );
                            else
                                dataRow[ currentFieldName ] = Strip( currentValue );
                        }
                        else
                        {
                            originalCommentsValue = currentValue;
                            currentValue = "<span class=\"commenttip1\"><a href=\"..\\Rollup%20Pages\\DepartmentComments.aspx?ProjectID=" + projectID + "&ListDeptName=" + allFieldViews[ j ][ "Source Department" ].ToString( ).Trim( ) + "\">";
                            if ( originalCommentsValue.Trim( ).Trim( ).Length > 63 )
                                currentValue += originalCommentsValue.Trim( ).Trim( ).Substring( 0, 63 ) + " ...";
                            else
                                if ( originalCommentsValue.Trim( ).Trim( ).Length == 0 )
                                    currentValue += "View History";
                                else
                                    currentValue += originalCommentsValue;

                            currentValue += "<span>";
                            if ( originalCommentsValue.Trim( ).Trim( ).Length > 150 )
                                currentValue += originalCommentsValue.Trim( ).Trim( ).Substring( 0, 150 ) + " ...";
                            else
                                if ( originalCommentsValue.Trim( ).Trim( ).Length == 0 )
                                    currentValue += "Current comment for this project does not exit.  Please click on View History link for previous comments.";
                                else
                                    currentValue += originalCommentsValue;

                            currentValue += "</span></a></span>";

                            dataRow[ currentFieldName ] = currentValue;
                        }
                    }
                    catch
                    {
                        ConsumeError( );
                    }
                }
                catch
                {
                    ConsumeError( );
                }
            }
        }

        public void GetNonDepartmentFields( SPWeb storeWeb, string sourceDepartment )
        {
            DepartmentFields deptFields = new DepartmentFields( );

            SPList currentDepartment = null;
            SPList departmentListValues = storeWeb.Lists[ "Department Administration List" ];
            SPQuery nonUserDepartments = new SPQuery( );

            nonUserDepartments.Query = "<Where><Eq><FieldRef Name='Department_x0020_Name' /><Value Type='Text'>" + sourceDepartment.Trim( ) + "</Value>   </Eq></Where>";
            nonUserDepartments.ViewFields = "<FieldRef Name='Department_x0020_Name'/>";
            SPListItemCollection otherDepartments = departmentListValues.GetItems( nonUserDepartments );
            foreach ( SPItem departmentItem in otherDepartments )
            {
                currentDepartment = storeWeb.Lists[ departmentItem[ "Department List Name" ].ToString( ).Trim( ) ];
                foreach ( SPField departmentField in currentDepartment.Fields )
                {
                    if ( !departmentField.Hidden && departmentField.FieldTypeDefinition.UserCreatable )
                    {
                        deptFields = new DepartmentFields( );
                        deptFields.DepartmentName = departmentItem[ "Department Name" ].ToString( ).Trim( );
                        deptFields.FieldName = departmentField.Title.Trim( );
                        deptFields.InternalFieldName = departmentField.InternalName.Trim( );

                        AvailableFields.Add( deptFields );
                    }
                }
            }
        }

        public void LoadDepartments( SPWeb storeWeb )
        {
            DepartmentInformation singleDepartment = new DepartmentInformation( );

            SPList departmentListValues = storeWeb.Lists[ "Department Administration List" ];
            foreach ( SPListItem item in departmentListValues.Items )
            {
                singleDepartment = new DepartmentInformation( );
                if ( item[ "Department Name" ] != null )
                    singleDepartment.DepartmentName = item[ "Department Name" ].ToString( );
                if ( item[ "Department List Name" ] != null )
                    singleDepartment.ListName = item[ "Department List Name" ].ToString( );
                if ( item[ "Department Security Group" ] != null )
                    singleDepartment.SecurityGroup = item[ "Department Security Group" ].ToString( );
                if ( item[ "Department Grid Code" ] != null )
                    singleDepartment.DepartmentCode = item[ "Department Grid Code" ].ToString( );

                DepartmentList.Add( singleDepartment );
            }
        }

        public List<DepartmentViewReferences> SelectUniqueColumnDepartmentsValues( SPWeb storeWeb, string sourceDepartment )
        {
            SPQuery nonUserDepartments = new SPQuery( );
            DepartmentViewReferences deptFields = new DepartmentViewReferences( );
            deptFields = null;
            string fieldsBuild = "<FieldRef Name='ID' />";
            List<DepartmentViewReferences> allFieldsByDepartment = new List<DepartmentViewReferences>( );
            SPList departmentListValues = storeWeb.Lists[ "Department Ordering Lookup" ];
            nonUserDepartments.Query = "<Where><Eq><FieldRef Name='Department_x0020_Owner' /><Value Type='Text'>" + sourceDepartment + "</Value></Eq></Where><OrderBy><FieldRef Name='Source_x0020_Department' Ascending='True' /></OrderBy>";
            nonUserDepartments.ViewFields = "<FieldRef Name='Source_x0020_Department' /><FieldRef Name='Department_x0020_Owner'/><FieldRef Name='Field_x0020_Name'/><FieldRef Name='Internal_x0020_Field_x0020_Name'/>";
            SPListItemCollection otherDepartments = departmentListValues.GetItems( nonUserDepartments );
            string currentDepartment = "";

            foreach ( SPListItem item in otherDepartments )
            {
                if ( !currentDepartment.Equals( item[ "Source Department" ].ToString( ) ) )
                {
                    if ( currentDepartment != string.Empty )
                    {
                        deptFields.AllFields = fieldsBuild;
                        allFieldsByDepartment.Add( deptFields );
                    }
                    deptFields = new DepartmentViewReferences( );
                    currentDepartment = item[ "Source Department" ].ToString( );
                    if ( currentDepartment.Equals( "Stores Detail" ) )
                        fieldsBuild = "<FieldRef Name='Reference_x0020__x0023_' />" + "<FieldRef Name='" + item[ "Internal Field Name" ].ToString( ) + "' />";
                    else
                        fieldsBuild = "<FieldRef Name='Store_x0020_Reference_x0020_ID' />" + "<FieldRef Name='" + item[ "Internal Field Name" ].ToString( ) + "' />";

                    deptFields.DepartmentName = currentDepartment;
                }
                else
                {
                    if ( item[ "Field Name" ].ToString( ).Equals( "Modified By" ) )
                        fieldsBuild += "<FieldRef Name='Editor' />";
                    else
                        fieldsBuild += "<FieldRef Name='" + item[ "Internal Field Name" ].ToString( ) + "' />";
                }
            }
            deptFields.AllFields = fieldsBuild;
            allFieldsByDepartment.Add( deptFields );
            return allFieldsByDepartment;
        }

        private static string DateStringCleanup( string input )
        {
            DateTime date;
            bool ok = DateTime.TryParse( input, out date );
            if ( ok )
                return date.ToShortDateString( );
            else
                return string.Empty;
        }

        void ConsumeError( )
        {
            const string Notice = "This method documents that errors encountered are ignored by design.";
        }

        #endregion Methods
    }
}